package ru.gerunn.test.callable;

import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
	
	public static class MyCallable implements Callable<String> {
		
		private String string;
		
		public MyCallable(String string) {
			this.string = string;
		}
		
		public String call() throws CallableException {
			System.out.println(this.string + " started");
			//if (string.matches("^0$")) throw new CallableException();
			return this.string;
		}
	}

	public static void main(String[] args) {
		int size = 10;
		String[] strings = new String[size];
		for (Integer i = 0; i < size; i++) strings[i] = i.toString();
		
		for ( String string : strings ) {
			System.out.println(string);
		}
		
		ExecutorService pool = Executors.newFixedThreadPool(size);
		ArrayList<Future<String>> list = new ArrayList<Future<String>>();
		
		for ( String string : strings ) {
			MyCallable callable = new MyCallable(string);
			Future<String> future = pool.submit(callable);
			list.add(future);
		}
		
		String ret = "";
		for (Future<String> future : list) {
			try {
				ret = ret + future.get();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
		
		System.out.println(ret);
		System.exit(0);
	}

}
